<template>
    <div class="login-container">
        <!-- 会有欢迎页面、登录页面 -->
        <div v-if="showWel" class="welcome">
            <!-- 这里定义的click事件是一个自定义事件，组件必须提供一个自定义事件触发 -->
            <!-- 可以给click事件添加一个native修饰符，让点击事件可以触发原生的click事件 -->
            <van-circle v-model="currentRate"
                :clockwise="false"
                layer-color="#f0f5ff"
                color="#10239e"
                size="48px"
                @click.native="closeEvt"
                :text="Math.ceil(currentRate / 20) + 's'"/>
            <img src="../../images/hclogo.png">
            <p>宏创OA办公</p>
            <span>{{welMsg}}</span>
        </div>
        <div v-else class="login-box">
            <div class="title">
                宏创OA办公
            </div>
            <div class="line u">
                <input v-model="phone" type="text" placeholder="输入手机号">
            </div>
            <div class="line">
                <input v-model="code" type="text" placeholder="输入验证码">
                <span @click="getCode">{{msg}}</span>
                <!-- <span>重新获取(60s)</span> -->
            </div>
            <div class="line no-icon on-border">
                <van-checkbox v-model="remember" checked-color="#10239e">记住手机号？</van-checkbox>
            </div>
            <div class="line no-icon on-border">
                <van-checkbox v-model="auto" checked-color="#10239e">是否同意免登录？</van-checkbox>
            </div>
            <van-button color="linear-gradient(to right, #10239e, #030852)"
                :disabled="!canSubmit"
                @click='submitEvt'
                type="primary" block>登录</van-button>
        </div>
        <span class="right">
            powered by qianfeng technology tcd. &copy;2022-
        </span>
    </div>
</template>

<script>
    import { autoLoginApi, loginApi, userInfoApi, userRoleApi, vdtCodeApi } from '@/apis/userApi'

    export default {
        computed: {
            canSubmit() {
                return /^1[3-9]{1}[0-9]{9}$/.test(this.phone) && /^[0-9]{4}$/.test(this.code)
            }
        },
        watch: {
            phone(val) {
                this.code = ''
            }
        },
        data() {
            return {
                remember: false,
                auto: false,
                showWel: true,
                currentRate: 100,
                welTimer: null,
                autoLogin: 'loading',
                welMsg: ['雪落无声，天地同色，人不出户',
                    '桃李初绽，大地新绿，柳醉轻烟',
                    '花开成群，蜂蝶自来，春色撩人',
                    '桃花殆尽，稚果才现，青红仍接',
                    '暑气才出，耀阳已照，郊游正好',
                    '天染深墨，雷雨交接，白珠入船',
                    '云似流火，满塘荷花，伞盖如云',
                    '三秋桂子，金黄初成，硕果压枝',
                    '秋来萧瑟，菊花独开，繁荣落寞',
                    '寒风始来，衣裳添厚，昼短夜长',
                    '新雪又来，火炉重置，辣椒添香',
                    '凛风刺骨，酒待新年，喧嚣驱寒'][new Date().getMonth()],
                phone: '',
                code: '',
                msg: '获取验证码',
                vdtTimer: null
            }
        },
        async created() {

            // 判断是否有免登录
            let autoToken = localStorage.getItem('auto-token')
            if (!!autoToken) {
                // 这个时候需要发送免登录请求--调用接口
                // 在发送请求之前把token先进行vuex缓存
                this.$store.commit('common/setToken', autoToken)
                sessionStorage.setItem('token', autoToken)
                let result = await autoLoginApi()
                if (result.code === 200) {
                    this.$store.commit('common/setUserInfo', result.data)

                    let userRole = await userRoleApi(result.data.role)
                    this.$store.commit('common/setUserRole', userRole.data)

                    this.autoLogin = 'success'
                } else {
                    // 免登录失败，那么用户可以点击关闭按钮，并且要去的页面是登录页面
                    // 那么免登录标识，应该有三个状态：正在请求--loading，请求失败--error，请求成功--success
                    this.autoLogin = 'error'
                }
            } else {
                this.autoLogin = 'error'
            }

            // 判断手机号是否缓存
            let phoneCache = localStorage.getItem('phone')
            if (!!phoneCache) {
                this.phone = phoneCache
                this.remember = true
            }

            this.welTimer = setInterval(() => {
                this.currentRate -= 1
                console.log('-----------------')
                if (this.currentRate < 1) {
                    /**
                     * 时间到了以后，要分情况进入不同的页面
                     * 如果有免登录并且登录成功，那么进入首页
                     * 否则进入登录页面
                     */
                    this.toPage()
                }
            }, 5000 / 100);
        },

        beforeDestroy() {
            clearTimeout(this.vdtTimer)
        },

        methods: {
            // 提交登录
            async submitEvt() {
                if (!this.canSubmit) return

                let result = await loginApi({
                    phone: this.phone,
                    vdtCode: this.code
                })
                if (result.code !== 200) {
                    this.$toast.fail('登录失败\n请重试')
                    return
                }

                this.$store.commit('common/setToken', result.data.token)
                sessionStorage.setItem('token', result.data.token)

                let userInfo = await userInfoApi(result.data.id)

                this.$store.commit('common/setUserInfo', userInfo.data)

                let userRole = await userRoleApi(userInfo.data.role)
                this.$store.commit('common/setUserRole', userRole.data)

                if (this.remember) {
                    localStorage.setItem('phone', this.phone)
                } else {
                    localStorage.removeItem('phone')
                }
                if (this.auto) {
                    localStorage.setItem('auto-token', result.data.token)
                } else {
                    localStorage.removeItem('auto-token')
                }

                this.$router.push('/work')
            },
            // 获取验证码
            async getCode() {
                // 判断节流标识
                if (this.msg !== '获取验证码') return
                if (!/^1[3-9]{1}[0-9]{9}$/.test(this.phone)) {
                    this.$toast({
                        message: '输入正确的手机号',
                        position: 'bottom',
                    })
                    return
                }
                this.msg = '获取中...'
                let result = await vdtCodeApi(this.phone)
                if (result.code !== 200) {
                    this.$toast.fail('获取验证码失败')
                    this.msg = '获取验证码'
                    return
                }

                this.$toast.success(`获取验证码\n${result.data.vdtCode}`)
                // 传递一个开始时间，后边是当前时间减去开始时间，得到过去了多少时间
                this.loop(Date.now())
            },
            loop(st) {
                let passTime = Math.ceil(60 - (Date.now() - st) / 1000)
                this.msg = `重新获取(${passTime}s)`
                this.vdtTimer = setTimeout(() => {
                    if (passTime > 0) {
                        this.loop(st)
                    } else {
                        this.msg = '获取验证码'
                        clearTimeout(this.vdtTimer)
                    }
                }, 200)
            },
            /**
             * 必须保证免登录接口调用完成以后
             * 调用失败，点击直接进入登录页面
             * 调用成功，要等获取用户信息等接口调用完成以后才能关闭
             */
            closeEvt() {
                if (this.autoLogin === 'loading') return
                this.toPage()
            },
            toPage() {
                clearInterval(this.welTimer)
                if (this.autoLogin === 'error') {
                    this.showWel = false
                } else {
                    this.$router.push('/home')
                }
            }
        }
    }
</script>

<style lang="less" scoped>
    @import "../../style/common.less";

    .right {
        display: block;
        position: absolute;
        bottom: 10px;
        left: 0;
        width: 100%;
        font-size: .6rem;
        text-align: center;
        color: @c8;
    }

    .login-box {
        display: block;
        position: relative;
        padding: 12vh 20px 0;
        > .title {
            &::before {
                content: '';
                display: inline-block;
                vertical-align: top;
                width: 36px;
                height: 36px;
                background: url(../../images/hclogo.png) center center / 32px 32px no-repeat;
            }
            line-height: 36px;
            text-align: center;
            font-size: .9rem;
            font-weight: 600;
            color: @c3;
            margin-bottom: 28px;
        }
        > .line {
            // line { &::before 表示css中的：line::before
            // &表示定义的样式和父级样式同级
            &::before {
                content: '';
                flex: 0 0 36px;
                vertical-align: middle;
                width: 36px;
                height: 36px;
                border-radius: 4px;
                background: url(../../images/lock.png) center center / 30px 30px no-repeat;
            }
            &.u::before {
                background-image: url(../../images/user.png);
            }
            display: flex;
            padding: 10px;
            line-height: 36px;
            border-bottom: solid 1px @c8;
            margin-bottom: 20px;
            input {
                flex: 1;
                // 用于解决flex撑破的方案
                width: 0;
                height: 36px;
                border: none;
                outline: none;
                background: transparent;
                font-size: .9rem;
                text-indent: 10px;
                font-weight: bold;
                color: @c3;
                &::-webkit-input-placeholder {
                    color: @c8;
                    font-size: .7rem;
                    font-weight: 400;
                }
            }
            > span {
                flex: 0 0 100px;
                height: 36px;
                line-height: 36px;
                text-align: center;
                border-left: solid 1px @c8;
                font-size: .65rem;
                color: @c3;
            }
            &.no-icon {
                &::before {
                    display: none;
                }
                margin-bottom: 10px;
            }
            &.on-border {
                border-bottom: none;
            }
        }
    }

    .van-circle {
        position: absolute;
        top: 10px;
        right: 10px;
    }

    .van-checkbox {
        font-size: .7rem;
        color: @c3!important;
    }

    .login-container {
        // 使用方法
        .my-box();
        > .welcome {
            .my-box();
            padding: 15vh 5vw 0;
            > img {
                display: block;
                width: 98px;
                height: 98px;
                margin: auto;
                border-radius: 10px;
            }
            > p {
                display: block;
                text-align: center;
                font-size: 1.1rem;
                font-weight: 600;
                color: @c3;
            }
            > span {
                display: block;
                text-align: center;
                font-size: .7rem;
                color: @c2;
            }
        }
    }
</style>